package com.celan.year2022.day1227;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class Solution {
    //nums = [-1,0,1,2,-1,-4]
    //[[-1,-1,2],[-1,0,1]]
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList();
        int len = nums.length;
        if (nums == null || len < 3) return ans;
        Arrays.sort(nums); // 排序
        for (int i = 0; i < len; i++) {
            if (nums[i] > 0) break; // 如果当前数字大于0，则三数之和一定大于0，所以结束循环
            if (i > 0 && nums[i] == nums[i - 1]) continue; // 去重
            int L = i + 1;
            int R = len - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    ans.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    while (L < R && nums[L] == nums[L + 1]) L++; // 去重
                    while (L < R && nums[R] == nums[R - 1]) R--; // 去重
                    L++;
                    R--;
                } else if (sum < 0) L++;
                else if (sum > 0) R--;
            }
        }
        return ans;
    }

    List<String> res = new ArrayList<>();
    StringBuilder path = new StringBuilder();
    HashMap<Integer, char[]> map = new HashMap<>();

    public List<String> letterCombinations(String digits) {
        map.put(2, new char[]{'a', 'b', 'c'});
        map.put(3, new char[]{'d', 'e', 'f'});
        map.put(4, new char[]{'g', 'h', 'i'});
        map.put(5, new char[]{'j', 'k', 'l'});
        map.put(6, new char[]{'m', 'n', 'o'});
        map.put(7, new char[]{'p', 'q', 'r', 's'});
        map.put(8, new char[]{'t', 'u', 'v'});
        map.put(9, new char[]{'w', 'x', 'y', 'z'});
        if (digits.length() < 1) return res;
        char[] chars = digits.toCharArray();
        backTrack(chars, 0);
        return res;
    }

    private void backTrack(char[] chars, int idx) {
        if (idx == chars.length) {
            String s = new String(path);
            res.add(s);
            return;
        }

        char[] select = map.get(chars[idx] - '0');
        for (int j = 0; j < select.length; j++) {
            path.append(select[j]);
            backTrack(chars, idx + 1);
            path.deleteCharAt(path.length() - 1);
        }

    }
}
